package com.sitanyun.merchant.guide.view.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.webkit.JavascriptInterface;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.CheckBox;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.kanfang123.viewersdk.KFWebView;
import com.kanfang123.viewersdk.VRViewerManager;
import com.kanfang123.viewersdk.ViewerStateListener;
import com.sitanyun.merchant.guide.R;
import com.sitanyun.merchant.guide.adapter.ScenUsersAdapter;
import com.sitanyun.merchant.guide.base.BaseActivity;
import com.sitanyun.merchant.guide.base.ToastUtil;
import com.sitanyun.merchant.guide.bean.DetailBean;
import com.sitanyun.merchant.guide.bean.ScenUserBean;
import com.sitanyun.merchant.guide.bean.UserVrBean;
import com.sitanyun.merchant.guide.callback.StringCallbacks;
import com.sitanyun.merchant.guide.presenter.impl.VrWebAPresenterImpl;
import com.sitanyun.merchant.guide.presenter.inter.IVrWebAPresenter;
import com.sitanyun.merchant.guide.url.Urls;
import com.sitanyun.merchant.guide.view.inter.IVrWebAView;
import com.sitanyun.merchant.guide.weiht.ActivityFinishUtil;
import com.sitanyun.merchant.guide.weiht.CheckAudioPermission;
import com.sitanyun.merchant.guide.weiht.DateUtils;
import com.sitanyun.merchant.guide.weiht.PermissionUtil;
import com.sitanyun.merchant.guide.weiht.PermissionsUtils;
import com.sitanyun.merchant.guide.weiht.PhoneUtils;
import com.sitanyun.merchant.guide.weiht.SPutils;
import com.sitanyun.merchant.guide.weiht.SharedPreferenceUtil;
import com.sitanyun.merchant.guide.weiht.WxShareUtils;
import com.tencent.imsdk.v2.V2TIMManager;
import com.tencent.imsdk.v2.V2TIMMessage;
import com.tencent.imsdk.v2.V2TIMSendCallback;
import com.zhy.http.okhttp.OkHttpUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;
import okhttp3.Call;

/**
 * web  VR
 */
public class VrWebActivity extends BaseActivity implements IVrWebAView {


    @BindView(R.id.user_popu)
    LinearLayout userPopu;
    @BindView(R.id.tv_return)
    ImageView tvReturn;
    @BindView(R.id.tv_title_str)
    TextView tvTitleStr;
    @BindView(R.id.image_right_key)
    ImageView imageRightKey;
    @BindView(R.id.tv_right_key)
    TextView tvRightKey;
    @BindView(R.id.ff_main_layout)
    FrameLayout ffMainLayout;
    @BindView(R.id.user_fx)
    ImageView userFx;
    @BindView(R.id.user_jt)
    LinearLayout userJt;
    @BindView(R.id.user_callphone)
    LinearLayout userCallphone;
    @BindView(R.id.user_online)
    TextView userOnline;
    @BindView(R.id.user_visit)
    TextView userVisit;
    @BindView(R.id.ll_bomm)
    LinearLayout llBomm;
    @BindView(R.id.cheaderimg)
    CircleImageView cheaderimg;
    @BindView(R.id.callimg)
    ImageView callimg;
    @BindView(R.id.callmessage)
    TextView callmessage;
    @BindView(R.id.tpimg)
    ImageView tpimg;
    @BindView(R.id.tpmessage)
    TextView tpmessage;
    @BindView(R.id.vr_webview)
    KFWebView webview;


    private String urls;
    private IVrWebAPresenter mIVrWebAPresenter;
    private ScenUsersAdapter scuseradapter;

    private ScenUserBean scenUserBean;
    private TextView poputvuser;
    private RecyclerView popurvlist;
    private byte[] bytes;
    private LinearLayout llone;
    private LinearLayout lltwo;
    private TextView inviteusers;

    private UserVrBean.CloudCustomDataBean cloudCustomDataBean = new UserVrBean.CloudCustomDataBean();
    private DetailBean detailBean;
    private String phone;
    private String picUrl;
    private String sceneUrl;
    private String sceneId;
    private Bitmap bitmap;
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 10:
                    if (bitmap != null) {
                        WxShareUtils.shareWxMin(VrWebActivity.this, "wx7cb638590873ca35"
                                , "VR全景逛，让您身临其境，乐享其中！", Urls.urls + "/v-show/index.html?" + sceneUrl,
                                "" + getIntent().getStringExtra("shops")+"("+getIntent().getStringExtra("names")+""+")",
                                "gh_5a0ad3d58ce7",
                                "pages/vr/vr?sceneId=" + sceneId
                                        + "&staffId=" + SharedPreferenceUtil.getStringData("staffid") + "&shareStaffId=" + SharedPreferenceUtil.getStringData("staffid")
                                , bitmap);
                    }
                    break;
            }
        }
    };
    private String type="";
    private String cid = "";
    private String state = "";
    private  int online;
    private Handler handlers = new Handler();
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            //在此处处理消息
            type="2";
            SPutils.clearAll();
            llBomm.setVisibility(View.VISIBLE);
            webview.loadUrl("javascript:window['KFMessageListener'].onAppEndTour(true);");
        }
    };
    private String sceneId1;

    @Override
    public int getLayoutId() {
        return R.layout.activity_vr_web;
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        //  setFindViewById(true);
        tvTitleStr.setText(getIntent().getStringExtra("names"));
        //setTitleStr(getIntent().getStringExtra("names"));
       // getWindow().setBackgroundDrawableResource(R.color.color_060218);// app主题颜色
        webview.setBackgroundColor(getResources().getColor(R.color.transparent));
        tvReturn.setVisibility(View.VISIBLE);
        mHandler.postDelayed(mRunnable, 600);
        //弹窗
        tvReturn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
           if (type.equals("4")||type.equals("1")||type.equals("3")){
               dialog();
           }  else {
               ActivityFinishUtil.finishOtherAllActivity(VrWebActivity.this);
               finish();
           }
            }
        });
        cid =getIntent().getStringExtra("cids");
        if (cid!=null) {
            //当前时间
            Date date = new Date(System.currentTimeMillis());
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// HH:mm:ss
            cloudCustomDataBean = new UserVrBean.CloudCustomDataBean(
                    "MEETING_INVITE",
                    SharedPreferenceUtil.getStringData("tonodeid")
                    , getIntent().getStringExtra("scenid")
                    , getIntent().getStringExtra("names")
                    ,getIntent().getStringExtra("storenodeid")
                    , getIntent().getStringExtra("shops")
                    , SharedPreferenceUtil.getStringData("staffid")
                    , SharedPreferenceUtil.getStringData("staffname")
                    , cid,
                    getIntent().getStringExtra("headname")+ "",
                    getIntent().getStringExtra("cphone")+ ""
                    , "0", simpleDateFormat.format(date));


        }
    }

    @Override
    protected void onResume() {
        super.onResume();


        //进入界面判断权限
   if (CheckAudioPermission.isVoicePermission()){
     //  ToastUtil.showToast(VrWebActivity.this,"有权限");
   }else {
       if (SharedPreferenceUtil.getStringData("pms").equals("0")){

       }else {
           permissiondialog(1);
       }

   }
    }

    //权限弹窗
    private void permissiondialog(int a) {
        //1、使用Dialog、设置style
        final Dialog dialog = new Dialog(VrWebActivity.this, R.style.DialogTheme);
        //2、设置布局
        View view = View.inflate(VrWebActivity.this, R.layout.permisen_dialog, null);
        dialog.setContentView(view);
        CheckBox cbpms=(CheckBox) view.findViewById(R.id.cb_pms);
        LinearLayout llpms=(LinearLayout) view.findViewById(R.id.ll_pms);

        if (a==0){
            llpms.setVisibility(View.GONE);
        }else {
            llpms.setVisibility(View.VISIBLE);
        }
        view.findViewById(R.id.tv_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                if (cbpms.isChecked()){
                   SharedPreferenceUtil.SaveData("pms","0");
                }else {
                    SharedPreferenceUtil.SaveData("pms","1");
                }
            }
        });
        view.findViewById(R.id.tv_setup).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                if (cbpms.isChecked()){
                    SharedPreferenceUtil.SaveData("pms","0");
                }else {
                    SharedPreferenceUtil.SaveData("pms","1");
                }
                PermissionUtil.gotoPermission(VrWebActivity.this);
            }
        });


        Window window = dialog.getWindow();
        //设置弹出位置
        window.setGravity(Gravity.CENTER);
        //  window.setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
        //设置弹出动画
        //   window.setWindowAnimations(R.style.main_menu_animStyle);
        //设置对话框大小
        window.setLayout(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
      dialog.setCancelable(false);
        dialog.show();
        /*添加View到当前显示的Activity*/
        //   MerchantApp.getInstance().showView(view);

    }
// //popu
    private Runnable mRunnable = new Runnable() {
        public void run() {
            // 弹出PopupWindow的具体代码
         //    mIVrWebAPresenter.getdetail(getIntent().getStringExtra("scenid"));
            if (!isFinishing()) {
                initpopu();
            }


        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
       // popupWindow.dismiss();
    }

    @SuppressLint("JavascriptInterface")
    @Override
    public void initView() {

        OkHttpUtils.get().url(Urls.detail).addParams("sceneId", getIntent().getStringExtra("scenid"))
                .addHeader("Authorization", "Bearer" + SharedPreferenceUtil.getStringData("token"))
                .build().execute(new StringCallbacks() {
            @Override
            public void onError(Call call, Exception e, int id) {
            }

            @Override
            public void onResponse(String response, int id) {
                detailBean = new Gson().fromJson(response, DetailBean.class);
                if (detailBean.getCode() == 0) {
                    DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    //1 当前时间 ，2到期时间
                    Date curDate = new Date(System.currentTimeMillis());//获取当前时间
                    String str = df.format(curDate);
                    try {
                        Date   one = df.parse(str);
                        Date  two = df.parse(detailBean.getData().getEndTime());
                        long time1 = one.getTime();
                        long time2 = two.getTime();

                        if(time1 >time2) {
                            initoverdue(detailBean.getData().getSaleName()+"",detailBean.getData().getSalePhone()+"");

                        }
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }



                    //   Glide.with(VrWebActivity.this).load(detailBean.getData().getPicUrl()).into(cheaderimg);
                    sceneId1 = detailBean.getData().getSceneId();
                    //-  1 4同屏请求接受  ，  其他正常进入场景
                        type = getIntent().getStringExtra("type");
                     //   Log.e("TYPE",type);
                        if (type.equals("4")){
                            //显示dialog
                            ActivityFinishUtil.addActivity(VrWebActivity.this);
//                 if (ActivityTaskManager.getInstance().containsName("vr")==false){
//                     ActivityTaskManager.getInstance().putActivity("vr",VrWebActivity.this);
//                 }
                            urls = getIntent().getStringExtra("urlss");
                          //  urls.replaceAll("vconsole=0", "vconsole=1");
                            if (!isFinishing()){
                                userOnline.setText(getIntent().getStringExtra("headname") + " 同屏中");
                                Glide.with(VrWebActivity.this).load(getIntent().getStringExtra("headurl")).error(R.mipmap.cimg).into(cheaderimg);

                            }
                            llBomm.setVisibility(View.GONE);
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                                new PermissionsUtils(VrWebActivity.this).requestPermissions(new String[]{Manifest.permission.RECORD_AUDIO
                                }, 100);

                            }

                         //   Log.e("NUM","4");

                        }else
                            if (type.equals("1")||type.equals("3")) {
                                if (!isFinishing()){
                                    userOnline.setText(getIntent().getStringExtra("headname") + " 同屏中");
                                    Glide.with(VrWebActivity.this).load(getIntent().getStringExtra("headurl")).error(R.mipmap.cimg).into(cheaderimg);

                                }
                                ActivityFinishUtil.addActivity(VrWebActivity.this);
                                urls = getIntent().getStringExtra("urlss");
                        if (!isFinishing()){
                            userOnline.setText(getIntent().getStringExtra("headname") + " 同屏中");
                            Glide.with(VrWebActivity.this).load(getIntent().getStringExtra("headurl")).error(R.mipmap.cimg).into(cheaderimg);

                        }

                        llBomm.setVisibility(View.GONE);
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                            new PermissionsUtils(VrWebActivity.this).requestPermissions(new String[]{Manifest.permission.RECORD_AUDIO
                            }, 100);

                        }

                    } else {
              ActivityFinishUtil.addActivity(VrWebActivity.this);
              llBomm.setVisibility(View.VISIBLE);
              //Urls.urls
                        urls = Urls.urls+"/v-show/index.html?" + detailBean.getData().getSceneUrl();
                    }
                    //VR
                    VRViewerManager.INSTANCE.registerViewerStateListener(new ViewerStateListener() {
                        @Override
                        public void onError(int i, String s, Bundle bundle) {

                            if (i == 1203) {
                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                                    new PermissionsUtils(VrWebActivity.this).requestPermissions(new String[]{Manifest.permission.RECORD_AUDIO
                                    }, 100);

                                }
                            }
                        }

                        @Override
                        public void onEnterRoomSuccess() {

                        }

                        @Override
                        public void onExitRoom(int i) {
                            if (i == 0) {
                                if (SPutils.getStringData("exim").equals("exims")) {

//                                    if (ActivityTaskManager.getInstance().containsName("vr")==true){
//                                        ActivityTaskManager.getInstance().removeActivity("vr");
//                                    }
                                 //   ActivityTaskManager.getInstance().removeActivity("vr");
                                    SPutils.SaveData("exim","end");
                           //     Log.e("TYPE","onexo+");
                                  type="4";
                                 initView();
                                }

                            }
                        }

                        @Override
                        public void onRemoteUserEnterRoom(String s) {

                        }

                        @Override
                        public void onRemoteUserLeaveRoom(String s) {

                        }

                        @Override
                        public void onNetworkQuality(String s, String s1) {

                        }

                        @Override
                        public void onExitVR() {
//                        if (SPutils.getStringData("exim").equals("end")){
//                           // ActivityTaskManager.getInstance().removeActivity("vrs");
//                            Thread thread = new Thread(){
//                                @Override
//                                public void run() {
//                                    super.run();
//                                    handler.sendEmptyMessage(0);
//                                }
//                            };
//                            thread.start();
                        //   llBomm.setVisibility(View.VISIBLE);
//                            type="2";
//                        }
                        }
                    });

/**
 * web  view设置
 */
                    webview.addJavascriptInterface(VrWebActivity.this, "WebViewJavascriptBridge");//添加js监听 这样html就能调用客户端
                    WebSettings webSettings = webview.getSettings();
                    webview.setWebChromeClient(new WebChromeClient());
                    webSettings.setJavaScriptEnabled(true);
                    webSettings.setDefaultTextEncodingName("GBK");
                    webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
                    webSettings.setTextZoom(100);
                    webSettings.setDomStorageEnabled(true);
                    webSettings.setDatabaseEnabled(true);
                    webSettings.setAllowFileAccess(true);
                    webSettings.setLoadsImagesAutomatically(true);
                    webSettings.setAllowFileAccessFromFileURLs(true);
                    webSettings.setAllowUniversalAccessFromFileURLs(true);
                    webSettings.setLoadWithOverviewMode(true);
                    webSettings.setUseWideViewPort(true);
                    webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
//                    webview.setOnTouchListener(new View.OnTouchListener() {
//                        @Override
//                        public boolean onTouch(View v, MotionEvent event) {
//                            ((WebView) v).requestDisallowInterceptTouchEvent(true);
//                            return false;
//                        }
//                    });
                    /**
                     * Step 3：注册该webview控件，并加载符合我们规范格式的Url
                     */

                    webview.setWebViewClient(new WebViewClient() {
                        // 重写此方法表明点击网页里面的链接还是在当前的webview里跳转，不跳到浏览器那边
                        @Override
                        public boolean shouldOverrideUrlLoading(WebView view, String url) {
                            //view.clearHistory();
                            return false;
                        }

                        // 重写此方法可以让webview处理https请求
                        @Override
                        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                            handler.proceed();
                        }
                    });
//                    webview.reload();//刷新
//                    webview.clearHistory();//清楚历史页面
              //  String vconsole=urls.replaceAll("vconsole=0", "vconsole=1");
                    VRViewerManager.INSTANCE.openViewer(webview);
                    webview.loadUrl(urls);

                }
            }
        });

    }
    //过期弹窗提示
    private void initoverdue(String name,String phone) {
        //1、使用Dialog、设置style
        final Dialog dialog = new Dialog(VrWebActivity.this, R.style.DialogTheme);
        //2、设置布局
        dialog.setCancelable(false);
        View view = View.inflate(VrWebActivity.this, R.layout.loginoutdialog_item, null);
        dialog.setContentView(view);
        TextView tsmessage = (TextView) view.findViewById(R.id.ts_message);
        TextView ts_messagetwo = (TextView) view.findViewById(R.id.ts_messagetwo);
        tsmessage.setText("您访问的场景已经到期，请联系");
        ts_messagetwo.setVisibility(View.VISIBLE);
        ts_messagetwo.setText("商务经理："+name+" "+phone);
        //取消
           view.findViewById(R.id.cancel).setVisibility(View.GONE);
        view.findViewById(R.id.cancelview).setVisibility(View.GONE);
        //确定
        view.findViewById(R.id.define).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
              finish();
            }
        });


        Window window = dialog.getWindow();
        //设置弹出位置
        window.setGravity(Gravity.CENTER);
        //  window.setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
        //设置弹出动画
        //   window.setWindowAnimations(R.style.main_menu_animStyle);
        //设置对话框大小
        window.setLayout(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        dialog.show();
        /*添加View到当前显示的Activity*/
        //   MerchantApp.getInstance().showView(view);
    }

    /**
     * @param userInfo
     */
    @SuppressLint("JavascriptInterface")
    @JavascriptInterface
    public void webMeetingEnd(String userInfo){
      //  ToastUtil.showToast(VrWebActivity.this,userInfo);
        Thread thread = new Thread(){
            @Override
            public void run() {
                super.run();
                handler.sendEmptyMessage(0);
            }
        };
        thread.start();
    }

    //同屏返回弹窗
    private void dialog() {
        //1、使用Dialog、设置style
        final Dialog dialog = new Dialog(VrWebActivity.this, R.style.DialogTheme);
        //2、设置布局
        View view = View.inflate(VrWebActivity.this, R.layout.finsh_vr, null);
        dialog.setContentView(view);
        view.findViewById(R.id.qx).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //////////////
               webview.loadUrl("javascript:window['KFMessageListener'].onAppEndTour(true);");
          //   webview.evaluateJavascript("javascript:if(KFMessageListener.onAppEndTour){KFMessageListener.onAppEndTour(true)}",null);
                SPutils.clearAll();
              dialog.dismiss();
//                finish();
              //  ActivityTaskManager.getInstance().closeAllActivity();
                ActivityFinishUtil.finishOtherAllActivity(VrWebActivity.this);
                finish();

            }
        });
        view.findViewById(R.id.qrz).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();

            }
        });


        Window window = dialog.getWindow();
        //设置弹出位置
        window.setGravity(Gravity.CENTER);
        //  window.setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
        //设置弹出动画
        //   window.setWindowAnimations(R.style.main_menu_animStyle);
        //设置对话框大小
        window.setLayout(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        dialog.show();
        /*添加View到当前显示的Activity*/
        //   MerchantApp.getInstance().showView(view);

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mIVrWebAPresenter = new VrWebAPresenterImpl(this);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);

    }


    /**
     * 权限申请返回结果
     *
     * @param requestCode  请求码
     * @param permissions  权限数组
     * @param grantResults 申请结果数组，里面都是int类型的数
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 100:
               if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { //同意权限申请
                //   SharedPreferenceUtil.SaveData("permission","ty");
               //    Toast.makeText(this, "权限接受了", Toast.LENGTH_SHORT).show();
                } else { //拒绝权限申请
                //   SharedPreferenceUtil.SaveData("permission","jj");
                 //   Toast.makeText(this, "权限被拒绝了", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
                break;
        }
    }

    @Override
    public <T> T request(int requestFlag) {
        return null;
    }

    @Override
    public <T> void response(T response, int responseFlag) {
        if (responseFlag == IVrWebAView.RESPONSE_ONE) {
            scenUserBean = (ScenUserBean) response;
            if (scenUserBean.getCode() == 0) {
                if (scenUserBean.getData().getList().size() == 0) {
                    llone.setVisibility(View.GONE);
                    lltwo.setVisibility(View.VISIBLE);
                    userOnline.setText("尚无用户浏览");
                    userVisit.setText("马上去邀请");
                    poputvuser.setText("今日共0人来访");
                    inviteusers.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            startActivity(new Intent(VrWebActivity.this, PosterActivity.class)
                                    .putExtra("shops", getIntent().getStringExtra("shops"))
                                    .putExtra("scenname", detailBean.getData().getSceneName())
                                    .putExtra("shar", detailBean.getData().getSceneUrl())
                                    .putExtra("scenid", detailBean.getData().getSceneId() + "")
                                    .putExtra("storeid", "" + detailBean.getData().getStoreNodeId()+"")
                                    .putExtra("storename", "" + detailBean.getData().getStoreName()+"")
                                    .putExtra("scenid", "" + getIntent().getStringExtra("scenid"))
                                    .putExtra("img", detailBean.getData().getPicUrl() + ""));
                        }
                    });
                } else {
                    llone.setVisibility(View.VISIBLE);
                    lltwo.setVisibility(View.GONE);
                    scuseradapter.setNewData(scenUserBean.getData().getList());
                    poputvuser.setText("今日共" + scenUserBean.getData().getVisitCount() + "人来访，" + scenUserBean.getData().getOnlineCount() + "人在线");
//                    if (cid!=null){
//                        for (int i = 0; i <scenUserBean.getData().getList().size() ; i++) {
//                            if (cid.equals(scenUserBean.getData().getList().get(i).getCId())){
//                                if (scenUserBean.getData().getList().get(i).getOnline()==0){
//                                    cid=null;
//                                }
//                            }
//                        }
//                    }
                    if (type.equals("4")||type.equals("1")||type.equals("3")){
                      //  popupWindow.dismiss();
                    }  else {
                        userOnline.setText(scenUserBean.getData().getOnlineCount() + "人正在浏览");
                    }
                 //   userOnline.setText(scenUserBean.getData().getOnlineCount() + "人正在浏览");
                    userVisit.setText(scenUserBean.getData().getOnlineCount() + "人在线" + scenUserBean.getData().getVisitCount() + "人看过");

                }

            } else {
                ToastUtil.showToast(VrWebActivity.this, scenUserBean.getMsg() + "");
            }

        }
    }

    /**
     * 场景详情请求
     *
     * @param response
     * @param responseFlag
     * @param <T>
     */
    @Override
    public <T> void responsedetail(T response, int responseFlag) {
       if (responseFlag == IVrWebAView.RESPONSE_ONE) {
 //           detailBean = (DetailBean) response;
//            if (detailBean.getCode() == 0) {
//                userOnline.setText(detailBean.getData().getBrowseNum() + "人正在浏览");
//                userVisit.setText(detailBean.getData().getShareNum() + "在线" + detailBean.getData().getMeetingNum() + "人看过");
//
//            } else {
//                ToastUtil.showToast(VrWebActivity.this, detailBean.getMsg() + "");
//            }
       }
    }

    /**
     * @param view
     * 点击事件
     */

    @OnClick({R.id.user_popu, R.id.user_fx, R.id.user_jt, R.id.user_callphone})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.user_popu:
                if (userOnline.getText().equals("尚无用户浏览")) {
                    startActivity(new Intent(VrWebActivity.this, PosterActivity.class)
                            .putExtra("shops", getIntent().getStringExtra("shops"))
                            .putExtra("scenname", detailBean.getData().getSceneName())
                            .putExtra("shar", detailBean.getData().getSceneUrl())
                            .putExtra("scenid", detailBean.getData().getSceneId() + "")
                            .putExtra("storeid", "" + getIntent().getStringExtra("storeid"))
                            .putExtra("storename", "" + detailBean.getData().getStoreName()+"")
                            .putExtra("scenid", "" + getIntent().getStringExtra("scenid"))
                            .putExtra("img", detailBean.getData().getPicUrl() + ""));

                } else {
                    initpopu();
                }

                break;
            case R.id.user_fx:
                //分享
                showBottomDialog();
                break;
            //同屏
            case R.id.user_jt:
                if (CheckAudioPermission.isVoicePermission()){
                    //  ToastUtil.showToast(VrWebActivity.this,"有权限");
                }else {
                    permissiondialog(0);
                    return;
                }
                if (DateUtils.isFastClick()) {
                    return ;
                }
                // 创建消息
                if (cid==null) {
                    ToastUtil.showToast(VrWebActivity.this, "请选择用户");
                    initpopu();
                    return;
                } else if (state.equals("已离线")) {
                    return;
                } else {
                    V2TIMMessage v2TIMMessage = V2TIMManager.getMessageManager().createCustomMessage("1".getBytes());
                    // 发送消息
                    String msg = JSON.toJSONString(cloudCustomDataBean);
                    v2TIMMessage.setCloudCustomData(msg);
                    V2TIMManager.getMessageManager().sendMessage(v2TIMMessage, "cid_" + cid, null, V2TIMMessage.V2TIM_PRIORITY_DEFAULT, false, null, new V2TIMSendCallback<V2TIMMessage>() {
                        @Override
                        public void onError(int code, String desc) {
                            Log.e("TAG", code + "" + desc);
                        }

                        @Override
                        public void onSuccess(V2TIMMessage v2TIMMessage) {
                            ToastUtil.showToast(VrWebActivity.this, "同屏讲解请求已发送");
                        }

                        @Override
                        public void onProgress(int progress) {
                            Log.e("TAG", "progress");
                        }
                    });
                }

                break;
                //打电话按钮
            case R.id.user_callphone:
                if (DateUtils.isFastClick()) {
                    return ;
                }
                if (phone == null) {
                    //   ToastUtil.showToast(VrWebActivity.this, "请选择用户");
                    // initpopu();
                    return;
                } else {
                    PhoneUtils.callPhone(VrWebActivity.this, phone);
                }
                break;
        }
    }

    //分享弹窗
    private void showBottomDialog() {
        //1、使用Dialog、设置style
        final Dialog dialog = new Dialog(this, R.style.DialogTheme);
        //2、设置布局
        View view = View.inflate(this, R.layout.wx_shar_popu, null);
        dialog.setContentView(view);
        TextView fxname = view.findViewById(R.id.fx_name);
        fxname.setText(detailBean.getData().getSceneName() + "");
        Window window = dialog.getWindow();
        //设置弹出位置
        window.setGravity(Gravity.BOTTOM);
        //设置弹出动画
        window.setWindowAnimations(R.style.main_menu_animStyle);
        //设置对话框大小
        window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        dialog.show();

        dialog.findViewById(R.id.wx_shars).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                sceneUrl = detailBean.getData().getSceneUrl();
                sceneId = getIntent().getStringExtra("scenid");
                picUrl = detailBean.getData().getPicUrl() + "";
                bitmap = returnBitMap(picUrl);
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// HH:mm:ss
                Date date = new Date(System.currentTimeMillis());
                cloudCustomDataBean = new UserVrBean.CloudCustomDataBean(
                        "SHARE",
                        SharedPreferenceUtil.getStringData("tonodeid")
                        , getIntent().getStringExtra("scenid")
                        , getIntent().getStringExtra("names")
                        ,detailBean.getData().getStoreNodeId()+""
                        , detailBean.getData().getStoreName()+""
                        , SharedPreferenceUtil.getStringData("staffid")
                        , SharedPreferenceUtil.getStringData("staffname")
                        , "1"
                        , ""
                        , ""
                        , "0", simpleDateFormat.format(date));
                V2TIMMessage v2TIMMessage = V2TIMManager.getMessageManager().createCustomMessage(sceneId.getBytes());
                // 发送消息
                String msgs = JSON.toJSONString(cloudCustomDataBean);
                v2TIMMessage.setCloudCustomData(msgs);
                V2TIMManager.getMessageManager().sendMessage(v2TIMMessage, "cid_1", null, V2TIMMessage.V2TIM_PRIORITY_DEFAULT, false, null, new V2TIMSendCallback<V2TIMMessage>() {
                    @Override
                    public void onError(int code, String desc) {
                        Log.e("SHARE", code + "" + desc);
                    }

                    @Override
                    public void onSuccess(V2TIMMessage v2TIMMessage) {
                        Log.e("SHARE", "onSuccess");
                    }

                    @Override
                    public void onProgress(int progress) {
                        Log.e("SHARE", "progress");
                    }
                });


                mHandler.sendEmptyMessageDelayed(10, 1000);

            }
        });
        //海报分享
        dialog.findViewById(R.id.hb_shars).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(VrWebActivity.this, PosterActivity.class)
                        .putExtra("shops", getIntent().getStringExtra("shops"))
                        .putExtra("scenname", detailBean.getData().getSceneName())
                        .putExtra("shar", detailBean.getData().getSceneUrl())
                        .putExtra("scenid", detailBean.getData().getSceneId() + "")
                        .putExtra("storeid", "" + detailBean.getData().getStoreNodeId()+"")
                        .putExtra("storename", "" + detailBean.getData().getStoreName()+"")
                        .putExtra("scenid", "" + getIntent().getStringExtra("scenid"))
                        .putExtra("img", detailBean.getData().getPicUrl() + ""));
                dialog.dismiss();
            }
        });
       //海报取消
        dialog.findViewById(R.id.shar_dismis).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });

    }

    //用户弹窗列表
    private void initpopu() {
//       String scenid= getIntent().getStringExtra("scenid");
        View contentView = LayoutInflater.from(VrWebActivity.this).inflate(
                R.layout.popu_item, null);
        llone = (LinearLayout) contentView.findViewById(R.id.ll_one);
        lltwo = (LinearLayout) contentView.findViewById(R.id.ll_two);
        inviteusers = (TextView) contentView.findViewById(R.id.inviteusers);

        popurvlist = (RecyclerView) contentView.findViewById(R.id.popu_rv_list);
        poputvuser = (TextView) contentView.findViewById(R.id.popu_tv_user);
        //创建布局管理
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        popurvlist.setLayoutManager(layoutManager);
        scuseradapter = new ScenUsersAdapter(VrWebActivity.this, cid);
        popurvlist.setAdapter(scuseradapter);
        scuseradapter.notifyDataSetChanged();
        mIVrWebAPresenter.getconsumerList(sceneId1);

        PopupWindow   popupWindow = new PopupWindow(contentView,
                950, ViewGroup.LayoutParams.MATCH_PARENT, true);

        popupWindow.setTouchable(true);

        popupWindow.setTouchInterceptor(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {

                //   Log.i("mengdd", "onTouch : ");

                return false;
                // 这里如果返回true的话，touch事件将被拦截
                // 拦截后 PopupWindow的onTouchEvent不被调用，这样点击外部区域无法dismiss
            }
        });

        // 如果不设置PopupWindow的背景，无论是点击外部区域还是Back键都无法dismiss弹框
        // 我觉得这里是API的一个bug
        popupWindow.setBackgroundDrawable(getResources().getDrawable(
                R.drawable.baise));

        // 设置好参数之后再show
        //  popupWindow.showAsDropDown(v);
        if (type.equals("4")||type.equals("1")||type.equals("3")){
            popupWindow.dismiss();
        }  else {
            popupWindow.showAtLocation(userPopu, Gravity.LEFT | Gravity.CENTER_HORIZONTAL, 0, 0);
        }

        //点击事件
        scuseradapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                phone = scuseradapter.getData().get(position).getPhone();
                if (phone == null) {
                    Glide.with(VrWebActivity.this).load(R.mipmap.callssame).into(callimg);
                    callmessage.setTextColor(Color.parseColor("#FFBEBCBC"));

                } else {
                    Glide.with(VrWebActivity.this).load(R.mipmap.callphone).into(callimg);
                    callmessage.setTextColor(Color.parseColor("#FFFFFF"));
                }
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// HH:mm:ss
                cid = scuseradapter.getData().get(position).getCId();
              //  online = scuseradapter.getData().get(position).getOnline();
                TextView lasthavior = (TextView) view.findViewById(R.id.lastBehavior);
                state = lasthavior.getText().toString().trim();
                userOnline.setText(scuseradapter.getData().get(position).getCName() + " " + lasthavior.getText().toString().trim());
                if (state.equals("已离线")) {
                    Glide.with(VrWebActivity.this).load(R.mipmap.same).into(tpimg);
                    tpmessage.setTextColor(Color.parseColor("#FFBEBCBC"));

                } else {
                    Glide.with(VrWebActivity.this).load(R.mipmap.erji).into(tpimg);
                    tpmessage.setTextColor(Color.parseColor("#FFFFFF"));

                }
                Glide.with(VrWebActivity.this).load(scuseradapter.getData().get(position).getHeadUrl()).into(cheaderimg);

                //当前时间
                Date date = new Date(System.currentTimeMillis());
                /**
                 * 1481591809093189634   志扬  cid
                 */
                cloudCustomDataBean = new UserVrBean.CloudCustomDataBean(
                        "MEETING_INVITE",
                        SharedPreferenceUtil.getStringData("tonodeid")
                        , getIntent().getStringExtra("scenid")
                        , getIntent().getStringExtra("names")
                        ,getIntent().getStringExtra("storenodeid")
                        ,  detailBean.getData().getStoreName()
                        , SharedPreferenceUtil.getStringData("staffid")
                        , SharedPreferenceUtil.getStringData("staffname")
                        , scenUserBean.getData().getList().get(position).getCId(),
                        scenUserBean.getData().getList().get(position).getCName() + "",
                        scenUserBean.getData().getList().get(position).getPhone() + ""
                        , "0", simpleDateFormat.format(date));

                popupWindow.dismiss();
            }
        });


    }

    //图片转换
    public Bitmap returnBitMap(final String url) {

        new Thread(new Runnable() {
            @Override
            public void run() {
                URL imageurl = null;

                try {
                    imageurl = new URL(url);
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                }
                try {
                    HttpURLConnection conn = (HttpURLConnection) imageurl.openConnection();
                    conn.setDoInput(true);
                    conn.connect();
                    InputStream is = conn.getInputStream();
                    bitmap = BitmapFactory.decodeStream(is);
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();

        return bitmap;
    }
//监听系统返回键
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            //-  1 同屏请求接受  ，  其他正常进入场景
            if (type.equals("1")||type.equals("3")||type.equals("4")) {
                dialog();
            } else {  //返回
                finish();
                ActivityFinishUtil.finishOtherAllActivity(VrWebActivity.this);
            }
        }
        return false;
    }
    @Override
    public void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }

    @Override
    public void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);

    }
    @Override
    protected void onPause() {
        super.onPause();
        webview.clearHistory();
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(String event) {
      // Log.e("TAGSSS",event);
        if (event.equals("end")){
           llBomm.setVisibility(View.VISIBLE);
            type="2";
           webview.loadUrl("javascript:window['KFMessageListener'].onAppEndTour(true);");
        }
    }
}
